const Router = require('koa-router')
const mongoose = require('mongoose')
const router = new Router()

router.post('/register', async ctx => {

  const User = require('../database/schema/User')

  const userName = await User.find({ userName: ctx.request.body.userName })
  if (userName.length) {
    ctx.body = {
      code: 500,
      message: '名字已被占用'
    }
  } else {
    let newUser = new User(ctx.request.body)

    await newUser.save().then(() => {
      ctx.body = {
        code: 200,
        message: '注册成功'
      }
    }).catch(error => {
      ctx.body = {
        code: 500,
        message: error
      }
    })
  }
})

router.post('/login', async ctx => {

  let loginUser = ctx.request.body
  let userName = loginUser.userName
  let password = loginUser.password

  const User = require('../database/schema/User')

  await User.findOne({ userName }).exec().then(async res => {
    if (res) {
      let newUser = new User()
      await newUser.comparePassword(password, res.password).then(isMatch => {
        ctx.body = {
          code: 200,
          data: isMatch
        }
      }).catch(error => {
        ctx.body = {
          code: 500,
          message: error
        }
      })
    } else {
      ctx.body = {
        code: 500,
        message: '用户名不存在'
      }
    }
  }).catch(error => {
    ctx.body = {
      code: 500,
      message: error
    }
  })
})

module.exports = router
